from django.conf import settings
from django.core.files.storage import Storage
from fdfs_client.client import Fdfs_client


class MyStorage(Storage):
    def __init__(self, BASE_URL=None):
        if not BASE_URL:
            BASE_URL = settings.BASE_URL
        self.BASE_URL = BASE_URL



    def open(self, name, mode='rb'):
        pass

    def save(self, name, content, max_length=None):
        # 保存对象时调用
        # 1.创建对象
        client = Fdfs_client(settings.FDFS_CONFIG)

        # 2.上传
        result = client.upload_appender_by_buffer(content.read())

        # 3.判断是否上传成功
        if result["Status"] != "Upload successed.":
            return None

        image_url = result["Remote file_id"]

        # 4.返回图片
        return image_url


    def exists(self, name):
        pass

    def url(self, name):
        return self.BASE_URL + name

